package online.heycm.platform.rocketmq.publisher;

import java.util.concurrent.ConcurrentHashMap;
import online.heycm.platform.common.entity.exception.Assert;
import online.heycm.platform.rocketmq.common.entity.Event;
import online.heycm.platform.rocketmq.common.handler.LocalTransactionHandler;

/**
 * 本地事务处理器注册中心
 *
 * @author heycm
 * @since 2023/12/2 20:30
 */
public class LocalTransactionHandlerRegistry {

    private static final ConcurrentHashMap<String, LocalTransactionHandler> REGISTRY = new ConcurrentHashMap<>();

    private LocalTransactionHandlerRegistry() {}

    public static void register(Event event) {
        Assert.notNull(event.getLocalTransactionHandler(), "LocalTransactionHandler is not allowed null.");
        String key = getKey(event);
        if (REGISTRY.containsKey(key)) {
            return;
        }
        REGISTRY.put(key, event.getLocalTransactionHandler());
    }

    public static LocalTransactionHandler get(Event event) {
        return REGISTRY.get(getKey(event));
    }

    private static String getKey(Event event) {
        return String.format("%s.%s", event.getEventTopic(), event.getEventName());
    }
}
